import { getTypeList, publish } from "../../../api/api";
import { useSelector } from "react-redux";
import moment from "moment";
import MarkdownIt from "markdown-it";
import { useEffect, useState, useRef } from "react";
import MdEditor from "react-markdown-editor-lite"
import "react-markdown-editor-lite/lib/index.css";
import "./_style.scss";
import { FileOutlined } from "@ant-design/icons";
import { Button, Select, Result } from "antd";
const {Option} = Select;
const mdParser = new MarkdownIt();
const Edit = () => {
  const [html, setHtml] = useState("");
  const [types, setTypes] = useState([]);
  const [title, setTitle] = useState("");
  const [typeID, setTypeID] = useState("");
  const [isSubmit, setIsSubmit] = useState(false);
  const refEdit = useRef()
  function handleEditorChange({html}) {    
    setHtml(html);
  };
  useEffect(() => {
    getTypeList().then(res => {
      setTypes(res.typeLists);
      setTypeID(res.typeLists[0].id);
    })
  }, [])
  const token = useSelector(state => state.user.loginInfo.token)
  const submitHtml = () => {
    publish({
      token,
      typeID,
      title,
      content: html,
      createdAt: moment().format("YYYY-MM-DD HH:mm:SS"),
    }).then(() => {
      setIsSubmit(true);
      refEdit.current.setText("");
      setTitle("");
      setTypeID(types[0].id);
    });
  };
  return (
    <div className="edit">
      <div className="submit_html">
        <Button type="primary" shape="circle" icon={<FileOutlined />} onClick={submitHtml} size="large" />
      </div>
      <div className="form">
        <div className="input_box">
          <input value={title} onChange={(e) => setTitle(e.target.value)} placeholder="输入标题"/> 
        </div>
        <div className="select_box">
          <Select value={typeID} onChange={(id) => setTypeID(id)}>
            {types.map(item => <Option key={item.id} value={item.id}>{item.type}</Option>)}
          </Select>
        </div>
      </div>
      {
        isSubmit && <div className="tip">
          <Result
            status="success"
            title={`文章${title}提交成功`}
            subTitle="分享给你的小伙伴吧!"
            extra={[
              <Button onClick={() => {setIsSubmit(false)}} type="primary" key="console">
                确认
              </Button>
            ]}
          />
        </div>
      }
      <MdEditor
        style={{ height: "600px" }}
        renderHTML={(text) => mdParser.render(text)}
        onChange={handleEditorChange}
        ref={refEdit}
      />
    </div>
  )
}

export default Edit;